# MessageGenerator - Generates Messages to the message bus
# Copyright (C) 2007 Lauri Taimila
# 
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

__licence__ = "GPLv2"
__copyright__ = "2007, Lauri Taimila"
__author__ = "Lauri Taimila <lauri@taimila.com>"


import threading
import time

from message import Message
from message_bus import MessageBus

class MessageGenerator(threading.Thread):
    """
    Thread that generates Messages to the Messagebus.
    """
    
    def __init__(self, message, message_bus, interval, offset):
        """
        Create a new message generator thread
        @param message: Message object
        @param message_bus: MessageBus object
        @param interval: Time interval in seconds
        @param offset: Wait this time at the beginning. This prevents all messages
                       to be generated at the same time (offset value is random)
        """
        threading.Thread.__init__(self)
        self.message = message            # Message to be generated
        self.message_bus = message_bus    # MessageBus where generated message is notified
        self.interval = interval          # Time interval
        self.offset = offset              # Offset time for this thread
        self.active = True                # Keep running flag
    
    def run(self):
        """Start generating messages"""
        time.sleep(self.offset)
        while True:
            time.sleep(self.interval)
            if not self.active:
                break
            self.message_bus.notifyMessage(self.message)
        
    def stopGenerator(self):
        """Stop generating messages"""
        self.active = False
